'use strict';

const Controller = require('egg').Controller;
const crypto = require('crypto');

class UserController extends Controller {
    async reg() {
        let { username, password, repassword } = this.ctx.request.body;
        this.ctx.validate({
            username: {
                type: "string",
                required: false,
                defValue: "",
                desc: "用户名称",
            },
            password: { type: "string", required: true, desc: "密码" },

        });
        if (await this.app.model.User.findOne({
            where: {
                username
            }
        })) {
            this.ctx.throw('400', "该用户已存在")
        }
        let res = await this.app.model.User.create({
            username, password
        })
        if (!res) {
            this.ctx.throw('500', "创建失败")

        }
        this.ctx.apiSuccess(res, "创建成功", 200);
    }
    async login() {
        this.ctx.body = "登录"
        let { username, password } = this.ctx.request.body;
        this.ctx.validate({
            username: {
                type: "string",
                required: false,
                defValue: "",
                desc: "用户名称",
            },
            password: { type: "string", required: true, desc: "密码" },

        });
        let res = await this.app.model.User.findOne({
            where: {
                username,
                status: 1
            },

        })
        if (!res) {
            this.ctx.throw(400, "用户已被禁用")
        }
        let res1 = await this.checkpasseord(password, res.password);
        if (!res1) {
            this.ctx.throw(500, "用户名或密码不正确")
        }
        res = JSON.parse(JSON.stringify(res))
        let token = await this.getToken(res)
        res.token = token
        if (!(await this.service.cache.set("user_" + res.id, token))) {
            this.ctx.throw(400, "登录失败")
        }

        console.log(token, "token")
        this.ctx.apiSuccess(res, "登录成功", 200)
    }
    async logout() {
        // this.ctx.authUser
        let currentuserid = this.ctx.authUser.id;
        if (!await this.service.cache.remove("user_" + currentuserid)) {
            this.ctx.throw(400, "退出登录失败")
        }
        this.ctx.apiSuccess("退出成功")
        // this.ctx.body="退出登录"
    }
    async checkpasseord(password, hashpassword) {
        const hmac = crypto.createHash("sha256", this.app.config.crypto.secret);
        hmac.update(password);
        password = hmac.digest("hex");

        return password === hashpassword;

    }
    async getToken(value) {
        return this.app.jwt.sign(value, this.app.config.jwt.secret);
    }
    async checktoken(token) {
        try {
            return this.app.jwt.verify(token, this.app.config.jwt.secret);
        } catch (err) {
            let fail = err.name === "TokenExpiredError"
                ? "token 已过期! 请重新获取令牌"
                : "Token 令牌不合法!";
            return this.ctx.apiFail(fail);
        }
    }
    async qrcode() {
        this.ctx.qrcode(JSON.stringify({
            id: this.ctx.params.id
        }));
    }
    async updateuser(){
        const currentid=this.ctx.authUser.id;
        this.ctx.validate({
            nickname: {
                type: "string", required: true, desc: "昵称"
            },
            avatar: {
                type: "string", required: true, desc: "头像"
            },
            username: {
                type: "string", required: true, desc: "微信号"
            },
        });
        let res=await this.ctx.model.User.findOne({
            where:{
                id:currentid
            }
        })
        if(!res){
            this.ctx.apiFail("该用户不存在")
        }
        res.username=this.ctx.request.body.username
        res.nickname=this.ctx.request.body.nickname
        res.avatar=this.ctx.request.body.avatar
        res.save();
        this.ctx.apiSuccess("修改成功")

    }

}

module.exports = UserController;
